/**
 * Created by xu_jiaHui on 2017/4/9.
 */
var actorId = sessionStorage.getItem("actorId");
$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_actorMenu/getActorMenuByActorId",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
                d.actorId = actorId;
            }
        },
        columns: [{
            data: "amId",
            targets: 0
        }, {
            data: "menuName"
        }, {
            data: "powerInsert",
            render: function (data, type, row) {
                var result;
                if (row.menuType == 1) {
                    result = "";
                } else {
                    if (data == 0) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 1 + ")'>" +
                            " <i class='fa fa-times'></i></button>"
                    } else if (data == 1) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 1 + ")'>" +
                            " <i class='fa fa-check'></i></button>"
                    }
                }
                return result;
            }
        }, {
            data: "powerDelete",
            render: function (data, type, row) {
                var result;
                if (row.menuType == 1) {
                    result = "";
                } else {
                    if (data == 0) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 2 + ")'>" +
                            " <i class='fa fa-times'></i></button>"
                    } else if (data == 1) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 2 + ")'>" +
                            " <i class='fa fa-check'></i></button>"
                    }
                }
                return result;
            }
        }, {
            data: "powerUpdate",
            render: function (data, type, row) {
                var result;
                if (row.menuType == 1) {
                    result = "";
                } else {
                    if (data == 0) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 3 + ")'>" +
                            " <i class='fa fa-times'></i></button>"
                    } else if (data == 1) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 3 + ")'>" +
                            " <i class='fa fa-check'></i></button>"
                    }
                }
                return result;
            }
        }, {
            data: "powerSelect",
            render: function (data, type, row) {
                var result;
                if (row.menuType == 1) {
                    result = "";
                } else {
                    if (data == 0) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 4 + ")'>" +
                            " <i class='fa fa-times'></i></button>"
                    } else if (data == 1) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 4 + ")'>" +
                            " <i class='fa fa-check'></i></button>"
                    }
                }
                return result;
            }
        }, {
            data: "powerCheck",
            render: function (data, type, row) {
                var result;
                if (row.menuType == 1) {
                    result = "";
                } else {
                    if (data == 0) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 5 + ")'>" +
                            " <i class='fa fa-times'></i></button>"
                    } else if (data == 1) {
                        result = "<button class='btn btn-default btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + "," + 5 + ")'>" +
                            " <i class='fa fa-check'></i></button>"
                    }
                }
                return result;
            }
        }, {
            data: "amId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                // var buttonInsert = "<button class='btn btn-default btn-xs btn-flat' onclick='$.addMenu()' title='添加'><i class='fa fa-plus-square'></i></button>";
                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteMenu(" + JSON.stringify(row) + ")' title='删除'><i class='fa fa-minus-square'></i></button>";
                var buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.updateMenu(" + JSON.stringify(row) + ")' title='编辑'><i class='fa fa-edit'></i></button>";
                var buttonOperation = "";
                // gInsert == 0 ? buttonOperation : buttonOperation += buttonInsert + " ";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate + " ";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;
                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><button type=\"button\" class=\"btn btn-primary btn-sm btn-flat \" id=\"goback\"> <i class='fa fa-arrow-left'></i> 返回</button> ";
            strToolBar += "<div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>"
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            var buttonInsert = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.addMenu()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            // 下拉工具栏不处理更新事件，但今后可能需要审核等功能，替换该位置即可
            //var buttonUpdate = "<li><button href='#' class='btn btn-warning btn-sm btn-flat btn-block' onclick='$.updateTeacher()'><i class='fa fa-edit'></i> 编辑</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            // 同上方更新事件同时处理
            //gUpdate == 0 ? strToolBar : strToolBar += buttonUpdate;
            strToolBar += "</ul></div> <div class='input-group input-group-sm'><input type='text' class='form-control' name='searchText' placeholder='页面'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);

            $("#goback").click(function () {
                //之前页面的权限
                var authority = sessionStorage.getItem("authority").split(",");
                $.loadURL('基础信息', '角色信息', "system/actor.html", authority[0], authority[1], authority[2], authority[3], authority[4])
            })

        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
});
// 搜索框查询操作
$.fn.searchDT = function () {
    // 注意gSelect查询权限的处理，由该表是否存在添加人或者审核人决定
    var searchContext = $("input[name='searchText']").val();
    gMainDT.search(searchContext).draw();
};
$.addMenu = function () {
    $("#label-menu").text("权限选择");
    $("#modal-menu").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
    $.ajax({
        url: "../rds_actorMenu/getMenu4List",
        type: 'post',
        dataType: 'json',
        success: function (msg) {
            var data = msg.jsonData;
            if (msg != null && typeof (msg) != "undefined") {
                var zNodes = new Array();
                for (var i = 0; i < data.length; i++) {
                    if (data[i].menuType == 1) {
                        var type = {
                            "id": data[i].menuId,
                            "pId": 0,
                            "name": data[i].menuName
                        };
                        zNodes[i] = type;
                    } else if (data[i].menuType == 2) {
                        var type = {
                            "id": data[i].menuId,
                            "pId": data[i].menuFather,
                            "name": data[i].menuName,
                        };
                        zNodes[i] = type;
                    }
                }

                var setting = {
                    check: {
                        enable: true,
                        radioType: "all"
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    }
                };

                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    var type = {"Y": "ps", "N": "ps"};
                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }

                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>" + str + "</li>");
                }

                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                setCheck();
                $("#py").bind("change", setCheck);
                $("#sy").bind("change", setCheck);
                $("#pn").bind("change", setCheck);
                $("#sn").bind("change", setCheck);

            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
}

function getChoosed() {
    var menuIds = "";
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = treeObj.getCheckedNodes(true),
        v = "";
    // console.log(nodes.length);
    for (var i = 0; i < nodes.length; i++) {
        v += nodes[i].name + ",";
        menuIds = menuIds + "," + nodes[i].id
    }
    menuIds = menuIds.substr(1, menuIds.length);
    // console.log(menuIds);
    $.ajax({
        url: "../rds_actorMenu/addMenu",
        type: 'post',
        dataType: 'json',
        data: {
            actorId: actorId,
            menuIds: menuIds
        },
        success: function (msg) {
            var data = msg.jsonData;
            if (msg != null && typeof (msg) != "undefined") {
                gMainDT.ajax.reload(null, false);
                $.alert("数据操作成功", 1)
                $("#modal-menu").modal("hide");
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
}

//更新权限
$.updateMenu = function (jsonData, data) {
    var powerInsert = jsonData.powerInsert;
    var powerDelete = jsonData.powerDelete;
    var powerUpdate = jsonData.powerUpdate;
    var powerSelect = jsonData.powerSelect;
    var powerCheck = jsonData.powerCheck;
    if (data == 1) {
        if (jsonData.powerInsert == 0) {
            powerInsert = 1;
        } else {
            powerInsert = 0;
        }
    } else if (data == 2) {
        if (jsonData.powerDelete == 0) {
            powerDelete = 1;
        } else {
            powerDelete = 0;
        }
    } else if (data == 3) {
        if (jsonData.powerUpdate == 0) {
            powerUpdate = 1;
        } else {
            powerUpdate = 0;
        }
    } else if (data == 4) {
        if (jsonData.powerSelect == 0) {
            powerSelect = 1;
        } else {
            powerSelect = 0;
        }
    } else if (data = 5) {
        if (jsonData.powerCheck == 0) {
            powerCheck = 1
        } else {
            powerCheck = 0;
        }
    }
    $.ajax({
        url: '../rds_actorMenu/updateActorMenu',
        type: 'post',
        dataType: 'json',
        data: {
            "amId": jsonData.amId,
            "powerInsert": powerInsert,
            "powerDelete": powerDelete,
            "powerUpdate": powerUpdate,
            "powerSelect": powerSelect,
            "powerCheck": powerCheck
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    if (msg.jsonData > 0) {
                        // $.alert("数据修改成功", 1);
                        gMainDT.ajax.reload(null, false);
                    } else {
                        $.alert("数据修改失败", 2);
                    }
                } else {
                    $.alert("数据修改失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function (msg) {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
};

//删除权限
$.deleteMenu = function (jsonData) {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该条数据（' + jsonData.menuName + '）吗?</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_actorMenu/deleteActorMenu',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "amId": jsonData.amId
                    },
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                if (msg.jsonData > 0) {
                                    $.alert("数据删除成功", 1);
                                    gMainDT.ajax.reload(null, false);
                                } else {
                                    $.alert("数据删除失败", 2);
                                }
                            } else {
                                $.alert("数据删除失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function (msg) {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};